package cn.time1024.time_app.ui.task

import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.fragment.app.Fragment
import cn.time1024.time_app.databinding.FragmentTaskDetailBinding
import com.example.timeassistant.network.ApiService
import com.example.timeassistant.network.ResponseEnvelope
import com.example.timeassistant.network.RetrofitClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class TaskDetailFragment : Fragment() {

    private var _binding: FragmentTaskDetailBinding? = null
    private val binding get() = _binding!!

    private var taskId: Long? = null
    private var selectedDue: String? = null
    private var isEditMode: Boolean = true

    private data class Subtask(var id: String, var name: String, var completed: Boolean)
    private val subtasks: MutableList<Subtask> = mutableListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val args = arguments
        taskId = args?.getLong("taskId")
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        _binding = FragmentTaskDetailBinding.inflate(inflater, container, false)
        setupHeader()
        setupPriority()
        setupPickers()
        setupSubtasks()
        setupComplete()
        setupSave()
        prefill()
        return binding.root
    }

    override fun onDestroyView() { super.onDestroyView(); _binding = null }

    /** 设置优先级选择（Spinner隐藏，点击标签弹窗选择） */
    private fun setupPriority() {
        val displayPriorities = arrayOf("高", "中", "低")
        val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, displayPriorities)
        binding.spPriority.adapter = adapter
        binding.prioritySelector.setOnClickListener {
            androidx.appcompat.app.AlertDialog.Builder(requireContext())
                .setTitle("选择优先级")
                .setItems(displayPriorities) { _, which ->
                    binding.spPriority.setSelection(which)
                    updatePriorityBadge()
                }
                .show()
        }
    }

    /** 设置日期时间选择器 */
    private fun setupPickers() {
        binding.btnPickDue.setOnClickListener {
            val cal = java.util.Calendar.getInstance()
            DatePickerDialog(requireContext(), { _, y, m, d ->
                TimePickerDialog(requireContext(), { _, h, min ->
                    val fmt = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.getDefault())
                    cal.set(y, m, d, h, min)
                    selectedDue = fmt.format(cal.time)
                    binding.tvDue.text = "截止日期: ${selectedDue}".trim()
                }, cal.get(java.util.Calendar.HOUR_OF_DAY), cal.get(java.util.Calendar.MINUTE), true).show()
            }, cal.get(java.util.Calendar.YEAR), cal.get(java.util.Calendar.MONTH), cal.get(java.util.Calendar.DAY_OF_MONTH)).show()
        }
    }

    /** 预填充数据并根据编辑模式切换展示 */
    private fun prefill() {
        val title = arguments?.getString("title")
        val desc = arguments?.getString("description")
        val due = arguments?.getString("dueDate")
        val priorityCode = arguments?.getString("priority") ?: "medium"
        binding.etTitle.setText(title ?: "")
        binding.tvTitleDisplay.text = title ?: ""
        binding.etDesc.setText(desc ?: "")
        binding.tvDescDisplay.text = desc ?: ""
        selectedDue = due
        binding.tvDue.text = "截止日期: ${selectedDue ?: "未选择"}".trim()
        val codes = arrayOf("high","medium","low")
        val idx = codes.indexOf(priorityCode)
        binding.spPriority.setSelection(if (idx>=0) idx else 1)
        updatePriorityBadge()
        applyEditMode()
    }

    /** 保存任务 */
    private fun setupSave() {
        binding.btnSave.setOnClickListener { performSave() }
        binding.btnEditSave.setOnClickListener {
            if (isEditMode) {
                performSave()
            }
            isEditMode = !isEditMode
            applyEditMode()
        }
    }

    /** 执行保存逻辑 */
    private fun performSave() {
        val title = binding.etTitle.text?.toString()?.trim()
        val desc = binding.etDesc.text?.toString()?.trim()
        if (title.isNullOrEmpty()) {
            Toast.makeText(requireContext(), "标题不能为空", Toast.LENGTH_SHORT).show(); return
        }
        val codes = arrayOf("high","medium","low")
        val payload = ApiService.TaskSubmit(
            taskId = taskId,
            title = title,
            description = desc,
            dueDate = selectedDue,
            priority = codes[binding.spPriority.selectedItemPosition]
        )
        val call = if (taskId == null) RetrofitClient.api.addTask(payload) else RetrofitClient.api.editTask(payload)
        call.enqueue(simpleVoidCallback("保存成功", "保存失败"))
    }

    /** 通用保存回调 */
    private fun simpleVoidCallback(successMsg: String, failMsg: String): Callback<ResponseEnvelope<Any?>> {
        return object : Callback<ResponseEnvelope<Any?>> {
            override fun onResponse(call: Call<ResponseEnvelope<Any?>>, response: Response<ResponseEnvelope<Any?>>) {
                val body = response.body()
                val ok = (body?.success == true) || (body?.code == "00000")
                if (response.isSuccessful && ok) {
                    Toast.makeText(requireContext(), successMsg, Toast.LENGTH_SHORT).show()
                    requireActivity().onBackPressedDispatcher.onBackPressed()
                } else {
                    Toast.makeText(requireContext(), body?.message ?: failMsg, Toast.LENGTH_SHORT).show()
                }
            }
            override fun onFailure(call: Call<ResponseEnvelope<Any?>>, t: Throwable) {
                Toast.makeText(requireContext(), "$failMsg：${t.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /** 顶部导航栏绑定 */
    private fun setupHeader() {
        binding.btnBack.setOnClickListener { requireActivity().onBackPressedDispatcher.onBackPressed() }
    }

    /** 更新优先级标签显示 */
    private fun updatePriorityBadge() {
        val displayPriorities = arrayOf("高", "中", "低")
        val idx = binding.spPriority.selectedItemPosition
        val label = displayPriorities[idx]
        binding.tvPriorityBadge.text = "${label}优先级"
    }

    /** 切换编辑模式展示 */
    private fun applyEditMode() {
        binding.btnEditSave.text = if (isEditMode) "保存" else "编辑"
        binding.etTitle.visibility = if (isEditMode) View.VISIBLE else View.GONE
        binding.tvTitleDisplay.visibility = if (isEditMode) View.GONE else View.VISIBLE
        binding.etDesc.visibility = if (isEditMode) View.VISIBLE else View.GONE
        binding.tvDescDisplay.visibility = if (isEditMode) View.GONE else View.VISIBLE
        binding.btnSave.visibility = if (isEditMode) View.VISIBLE else View.GONE
        binding.btnPickDue.visibility = if (isEditMode) View.VISIBLE else View.GONE
    }

    /** 子任务区域 */
    private fun setupSubtasks() {
        binding.btnAddSubtask.setOnClickListener {
            val id = "sub${System.currentTimeMillis()}"
            subtasks.add(Subtask(id, "", false))
            renderSubtasks()
        }
        renderSubtasks()
    }

    /** 渲染子任务列表 */
    private fun renderSubtasks() {
        val container = binding.containerSubtasks
        container.removeAllViews()
        val inflater = LayoutInflater.from(requireContext())
        subtasks.forEach { sub ->
            val row = android.widget.LinearLayout(requireContext()).apply {
                orientation = android.widget.LinearLayout.HORIZONTAL
                setPadding(0, 12, 0, 12)
                gravity = android.view.Gravity.CENTER_VERTICAL
            }
            val cb = android.widget.CheckBox(requireContext()).apply {
                isChecked = sub.completed
                setOnCheckedChangeListener { _, checked -> sub.completed = checked }
            }
            val et = android.widget.EditText(requireContext()).apply {
                layoutParams = ViewGroup.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT)
                hint = "输入子任务名称"
                setText(sub.name)
                setOnFocusChangeListener { _, _ -> sub.name = text?.toString()?.trim().orEmpty() }
            }
            (et.layoutParams as ViewGroup.LayoutParams).width = 0
            row.addView(cb)
            row.addView(et)
            container.addView(row)
        }
    }

    /** 标记完成 */
    private fun setupComplete() {
        binding.btnComplete.setOnClickListener {
            if (taskId == null) {
                Toast.makeText(requireContext(), "保存后可标记完成", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            androidx.appcompat.app.AlertDialog.Builder(requireContext())
                .setTitle("确认完成")
                .setMessage("确定要标记此任务为完成吗？")
                .setPositiveButton("确定") { _, _ ->
                    RetrofitClient.api.updateTaskStatus(ApiService.TaskSubmit(taskId = taskId, completed = true))
                        .enqueue(simpleVoidCallback("任务已完成", "操作失败"))
                }
                .setNegativeButton("取消", null)
                .show()
        }
    }
}
